package com.example.sunmiv1.vm

import android.app.Activity
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.example.sunmiv1.entity.PrintInfoBean
import com.example.sunmiv1.entity.PrintInfoBean.DataBean.GoodsBean
import com.example.sunmiv1.listener.TextChangeListener
import com.example.sunmiv1.room.MerchandiseDaoManager
import com.example.sunmiv1.room.OrderManager
import com.example.sunmiv1.room.entity.MerchandisePrintEntity
import com.example.sunmiv1.room.entity.OrderEntity
import com.example.sunmiv1.utils.GsonTools
import com.example.sunmiv1.utils.MathUtil
import com.example.sunmiv1.utils.net.ACache
import kotlinx.android.synthetic.main.activity_choose_payment.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.CopyOnWriteArrayList


class ChoosePaymentViewModel(private val mActivity:Activity){
    private val TAG=javaClass.simpleName
    private val mACache by lazy {
        ACache.get(mActivity)
    }
    private val mList= CopyOnWriteArrayList<MerchandisePrintEntity>()
    private val mSp by lazy {
        mActivity.getSharedPreferences("print_setting",Activity.MODE_PRIVATE)
    }
    private var mMoneyTextChangeListener:TextChangeListener?=null
    private var mMoney=0.0
    fun init(){
        GlobalScope.launch(Dispatchers.IO){
            val list= MerchandiseDaoManager.getAll()
            mList.clear()
            mList.addAll(list)
        }
        initView()
    }
    private fun initView(){
        with(mActivity){
            check_print_icon.isChecked=mSp.getBoolean("isPrint",true)
            check_print_sku_icon.isChecked=mSp.getBoolean("isPrintSku",true)
            check_print_tv.text=if(check_print_icon.isChecked){
                "打印收據"
            }else{
                "不印收據"
            }
            check_print_sku_tv.text=if(check_print_sku_icon.isChecked){
                "打印品项"
            }else{
                "不印品項"
            }
            check_print_icon.setOnCheckedChangeListener { buttonView, isChecked ->
                mSp.edit().putBoolean("isPrint",isChecked).apply()
                initView()
            }
            check_print_sku_icon.setOnCheckedChangeListener { buttonView, isChecked ->
                mSp.edit().putBoolean("isPrintSku",isChecked).apply()
                initView()
            }
        }
        mActivity.choosePayment_otherPay_payable.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                mMoneyTextChangeListener?.onTextChange(s?.toString()?:"")
                if(mMoney<=0){
                    return
                }
                val v=MathUtil.sub(getMoneyValue(),mMoney)
                if(v<0){
                    mActivity.change_edit.text="$v"
                }else{
                    mActivity.change_edit.text="$v"
                }
            }
        })
    }
    fun isPrint()=mSp.getBoolean("isPrint",true)
    fun isPrintSku()=mSp.getBoolean("isPrintSku",true)
    fun getPrintInfo(bean: PrintInfoBean):PrintInfoBean{
        Log.e(TAG, "getPrintInfo: json=${GsonTools.beanToJson(bean)}")
        Log.e(TAG, "getPrintInfo: list=${GsonTools.beanToJson(mList)}")
        val list= arrayListOf<GoodsBean>()
        bean.data?.goods?.forEach {item->
            val first=mList.firstOrNull {
                it.merchandiseName==item.goods_name
            }
            if(first==null || first.isPrint){
                list.add(item)
            }
        }
        bean.data?.goods=list
        if(!isPrintSku()){
            bean.data?.goods?.forEach { 
                it.sku_name=""
            }
        }
        Log.e(TAG, "getPrintInfo: end=${GsonTools.beanToJson(bean)}")
        return bean
    }
    fun addRemake(orderNo:String){
        val v=mActivity.remark_edit.editableText.toString()
        if(v.isBlank()){
            return
        }
        GlobalScope.launch(Dispatchers.IO){
            val list=OrderManager.findOrderNo(orderNo)
            if(list.isEmpty()){
                OrderManager.add(OrderEntity().also {
                    it.orderNo=orderNo
                    it.remake=v
                })
            }else{
                OrderManager.update(OrderEntity().also {
                    it.orderNo=orderNo
                    it.remake=v
                })
            }
        }
    }
    fun setMoneyTextListener(listener: TextChangeListener?){
        mMoneyTextChangeListener=listener
    }
    fun setMoney(v:Double){
        mMoney=v
    }
    fun getMoney()=mMoney
    fun getMoneyEditValue():Double{
        val value=mActivity.choosePayment_realPay.editableText.toString()
        Log.e(TAG, "getMoneyEditValue: value=$value")
        if(value.isBlank()){
            return 0.00
        }
        if(value.substring(value.length-1)=="."){
            return value.substring(0,value.length-1).toDoubleOrNull()?:0.00
        }
        return value.toDoubleOrNull()?:0.00
    }
    fun getChangeEditValue():Double{
        val value=mActivity.choosePayment_smallChange.text.toString()
        Log.e(TAG, "getChangeEditValue: value=$value")
        if(value.isBlank()){
            return 0.00
        }
        if(value.substring(value.length-1)=="."){
            return value.substring(0,value.length-1).toDoubleOrNull()?:0.00
        }
        return value.toDoubleOrNull()?:0.00
    }
    fun getMoneyValue():Double{
        val value=mActivity.choosePayment_otherPay_payable.editableText.toString()
        Log.e(TAG, "getMoneyValue: value=$value")
        if(value.isBlank()){
            return 0.00
        }
        if(value.substring(value.length-1)=="."){
            return value.substring(0,value.length-1).toDoubleOrNull()?:0.00
        }
        return value.toDoubleOrNull()?:0.00
    }
    fun getChangeValue():Double{
        val value=mActivity.change_edit.text.toString()
        Log.e(TAG, "getChangeValue: value=$value")
        if(value.isBlank()){
            return 0.00
        }
        if(value.substring(value.length-1)=="."){
            return value.substring(0,value.length-1).toDoubleOrNull()?:0.00
        }
        return value.toDoubleOrNull()?:0.00
    }
    fun showMoneyEdit(){
        mActivity.choosePayment_realPay.also {
            it.requestFocus()
            val imm = mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
            imm!!.showSoftInput(it, InputMethodManager.SHOW_IMPLICIT)
        }
    }
    fun updateChange(vis:Boolean){
        val v=if(vis){
            View.VISIBLE
        }else{
            View.GONE
        }
        mActivity.change_view.visibility=v
    }
    fun getChangeMoney()=-MathUtil.sub(getMoneyValue(),mMoney)
    fun log(){
        ACache.get(mActivity).also {
            val id1=it.getAsString("storeid")
            val id2=it.getAsString("merchantid")
            Log.e(TAG, "log: value=$id1===$id2", )
        }
    }
}